package com.itheima.blog.admin.interceptor;

import com.itheima.api.client.User.UserClient;
import com.itheima.api.client.entity.AdminUser;
import com.itheima.blog.admin.entity.OperationLogTable;
import com.itheima.blog.admin.service.IOperationLogTableService;
import com.itheima.blog.util.DateUtil;
import com.itheima.blog.util.UserThreadLocalUtils;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
@RequiredArgsConstructor
@Slf4j
public class adminAspect {
    @Pointcut("execution (* com.itheima.blog.admin.controller.*.*(..)))")
    public void path(){}
    public static Date startTime = new Date();
    public static OperationLogTable logTable = new OperationLogTable();
    private final RestTemplate restTemplate;
    private final UserClient adminUserClient;
    private final IOperationLogTableService operationLogTableService;
//    @Before("path()")
//    public void startRecording(){
//
//    }
    @Around("path()")
    @Transactional
    public Object around(ProceedingJoinPoint joinPoint ) throws Throwable {
        log.info("开始记录：");
        logTable.setTime(LocalDateTime.now());

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        logTable.setInterfaceName(method.getAnnotation(ApiOperation.class).value());
        if (method.getAnnotation(PostMapping.class)!=null){
            logTable.setRequestMethod("Post");
            String[] value = method.getAnnotation(PostMapping.class).value();
            logTable.setAccessInterface(value[0]);
        }
        if (method.getAnnotation(GetMapping.class)!=null){
            logTable.setRequestMethod("Get");
            String[] value = method.getAnnotation(GetMapping.class).value();
            logTable.setAccessInterface(value[0]);
        }
        if (method.getAnnotation(DeleteMapping.class)!=null){
            logTable.setRequestMethod("Delete");
            String[] value = method.getAnnotation(DeleteMapping.class).value();
            logTable.setAccessInterface(value[0]);
        }
        if (method.getAnnotation(PutMapping.class)!=null){
            logTable.setRequestMethod("Put");
            String[] value = method.getAnnotation(PutMapping.class).value();
            logTable.setAccessInterface(value[0]);
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        logTable.setIp(ip);
        String url = "https://api.map.baidu.com/location/ip?ip="+ ip +"&ak=UqzVwULxM5Z1PlaWtnEkpD67uDd3S5Cc";
        //1. getForObject()
        //先获取返回的字符串，若想获取属性，可以使用json转化为实体后get方法获取
        String result = restTemplate.getForObject(url, String.class);
        String[] split = result.split("\"");
        String[] split1 = split[3].split("|");
        logTable.setEconomize(split1[1]);
        logTable.setKingdom("中国");
        Integer adminUserId = UserThreadLocalUtils.getAdminUserId();
        AdminUser adminUser = adminUserClient.getAdminUser(adminUserId);
        logTable.setUserName(adminUser.getName());
        Object proceed = joinPoint.proceed();

        long consuming = new Date().getTime() - startTime.getTime();
        logTable.setTimeConsuming(consuming);
        if (consuming > 80){
            logTable.setState("超时");
        }else if (consuming > 1){
            logTable.setState("一般 ");
        }else {
            logTable.setState("正常");
        }
        logTable.setCreationTime(LocalDateTime.now());
        logTable.setId(Long.valueOf(DateUtil.dateToString("MMddHHmmssSS")+(int)(Math.random()*90000 + 10000)));
        operationLogTableService.save(logTable);
        return proceed;
    }

//    @After("path()")
//    public void endRecording(){
//
//    }
}
